package com.xm.component.easyexport;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DefaultListConverter<E, R> implements Converter<List<E>, R> {
    /**
     * @param modelClass excel模型
     * @param list       目标方法返回的 list
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<R> convert(Class<R> modelClass, List<E> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        final E first = list.get(0);

        if (first == null) {
            return new ArrayList<>();
        }
        if (first.getClass() == modelClass) {
            return (List<R>) list;
        }
        return list.stream().map(e -> {
            try {
                final R r = modelClass.newInstance();
                BeanUtils.copyProperties(e, r);
                return r;
            } catch (InstantiationException | IllegalAccessException ex) {
                throw new RuntimeException(ex);
            }
        }).collect(Collectors.toList());
    }
}
